package com.example.demo.filter;


import com.alibaba.fastjson.JSON;
import com.example.demo.DTO.ResultDTO;
import com.example.demo.entity.User;
import com.example.demo.util.FilterUtil;
import com.example.demo.util.RedisUtil;
import com.example.demo.util.TokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.scanner.Constant;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/**
 * @author moguai
 * @version 1.0
 * @date 2022/3/18 23:01
 */
@Component
@WebFilter(urlPatterns = {"/api/*", "/user/loginout"}, filterName = "tokenAuthorFilter")
public class TokenAuthorFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(TokenAuthorFilter.class);
    @Autowired
    FilterUtil filterUtil;
    @Autowired
    TokenUtils tokenUtils;
    @Autowired
    RedisUtil redisUtil;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        filterUtil.filterSetting(rep);
        String token = req.getHeader("token");//header方式
        ResultDTO resultInfo = new ResultDTO();
        String method = ((HttpServletRequest) request).getMethod();
        //过滤掉OPTIONS 类型的请求
        if (method.equals("OPTIONS")) {
            rep.setStatus(HttpServletResponse.SC_OK);
        }
        if (tokenUtils.isTokenWhite(token)) {
            resultInfo.setCode(200);
            resultInfo.setMessage("用户授权认证通过!");
            String id=redisUtil.getValue(token);
            req.setAttribute("user", Integer.valueOf(id));
            chain.doFilter(request, response);
        } else {
            resultInfo.setCode(5000);
            resultInfo.setMessage("用户授权认证没有通过!客户端请求参数token信息无效");
            filterUtil.outPut(response,resultInfo);
            return;
        }
    }
}
